using System;
using System.Reflection;

namespace Behaviours.Events.EventBus
{
    internal class EventHandlerWraper
    {
        private delegate void MethodIpl(Event o);

        private MethodIpl methodProxy;
        public EventHandlerWraper(object handler, MethodInfo methodInfo, int evntType)
        {
            Handler = handler;
            MethodInfo = methodInfo;
            EventType = evntType;
            methodProxy = CreateDelegate<MethodIpl>(methodInfo,handler);
        }

        public object Handler { get; }

        public MethodInfo MethodInfo { get; }

        public int EventType { get; }

        public void Handle(Event o)
        {
            if(methodProxy != null)
                methodProxy(o);
        }
        private V CreateDelegate<V>(MethodInfo method, Object target) where V : class
        {
            var ret = (Delegate.CreateDelegate(typeof(V), target, method) as V);
            if (ret == null)
            {
                throw new ArgumentException("Unabled to create delegate for method called " + method.Name);
            }
            return ret;
        }
    }
}
